package com.tecklab.demo.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.tecklab.demo.aspect.OperateLog;
import com.tecklab.demo.common.BizException;
import com.tecklab.demo.common.Result;
import com.tecklab.demo.entity.HospitalEntity;
import com.tecklab.demo.entity.UserEntity;
import com.tecklab.demo.mapper.UserMapper;
import com.tecklab.demo.service.UserService;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class UserServiceImpl implements UserService {

    // 注入UserMapper.......依赖的Mapper
    private final UserMapper userMapper;

    /**
     * 构造方法注入
     * UserServiceImpl类的构造方法（Constructor）,而不是普通方法。UserServiceImpl：方法名与类名相同，表明它是构造方法。
     * 这是一个构造方法，用于创建 UserServiceImpl对象时依赖注入（Dependency Injection）UserMapper的实例。
     * 将传入的 userMapper参数赋值给当前类的成员变量 this.userMapper。
     * this.userMapper = userMapper将参数值赋给类的成员变量（需提前定义，如 private final UserMapper userMapper;）。
     **/
    public UserServiceImpl(UserMapper userMapper) {
        this.userMapper = userMapper;
    }

    @Override
    public UserEntity login(String username, String password) {
        //调佣Mapper方法
        return userMapper.findByUsernameAndPassword(username, password);
    }

    @Override
    public List<UserEntity> getAllUsers() {
        return userMapper.selectList(null);
    }

    @Override
    public UserEntity getUserById(Integer id) {
        return userMapper.selectById(id);
    }

    @Override
    public int addUser(UserEntity user) {
        return userMapper.insert(user);
    }

    @Override
    public UserEntity updateUser(Integer id, UserEntity user) {
        user.setId(id);
        userMapper.updateById(user);
        return user;
    }

    @Override
    public void deleteUser(Integer id) {
        // 修改:userMapper.deleteById(id);
        userMapper.deleteById(id);
    }

    @Override
    public boolean existsByUsername(String username) {
        return userMapper.existsByUsername(username);
    }

    @Override
    public boolean isAdmin(Integer id) {
        UserEntity user = userMapper.selectById(id);
        if (user.getAccountType() == 1) {
            return true;
        }
        return false;
    }

    @Override
    public void batchCreateUser(int size) {
        QueryWrapper<UserEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("id")
                .last("limit 1")
                .select("id");
        UserEntity userEntity = userMapper.selectOne(queryWrapper);
        int startId = (userEntity == null) ? 1 : userEntity.getId() + 1;
        for (int i = startId; i < (startId + size); i++) {
            UserEntity entity = new UserEntity();
            entity.setAccountType(2);
            entity.setStatus(1);
            entity.setUsername("zyy" + i);
            entity.setPassword("123456");
            entity.setEmail(entity.getUsername() + "@163.com");
            userMapper.insert(entity);
        }
    }

    @Override
    public Result batchDeleteUser(List<Integer> idList) {
        List<UserEntity> userList = userMapper.selectList(new QueryWrapper<UserEntity>().lambda().in(UserEntity::getId, idList));
        if (CollectionUtils.isEmpty(userList)) {
            throw new BizException("用户不存在");
        }

        Map<Integer, UserEntity> userMap = userList.stream().collect(Collectors.toMap(UserEntity::getId, user -> user));
        List<Integer> toDeleteList = new ArrayList<>();
        for (Integer id : idList) {
            UserEntity user = userMap.get(id);
            if (user.getAccountType() == 2) {
                toDeleteList.add(id);
            }
        }
        if (toDeleteList.size() > 0) {
            userMapper.deleteBatchIds(toDeleteList);
            for (Integer id : toDeleteList) {
                StpUtil.kickout(id);
            }
        }
        return Result.success(String.format("成功删除用户%d个，其中有%d个管理员不能删除", toDeleteList.size(), idList.size() - toDeleteList.size()));
    }

    @Override
    //批量重置密码，但不能重置管理员的密码
    public Result<String> batchResetPwd(List<Integer> idList) {
        // 1.根据ID查询获取用户列表，
        List<UserEntity> userList = userMapper.selectList(new QueryWrapper<UserEntity>().lambda().in(UserEntity::getId, idList));
        if (CollectionUtils.isEmpty(userList)) {
            throw new BizException("用户不存在");
        }
        // 将用户列表转换为Map，key为用户ID，value为用户对象，方便后续按ID快速查找
        Map<Integer, UserEntity> userMap = new HashMap<>();
        for (UserEntity user : userList) {
            userMap.put(user.getId(), user);
        }
        // 创建需要重置密码的用户ID列表
        List<Integer> toResetList = new ArrayList<>();
        // 2.判断用户类型：如果是普通用户，才能重置密码
        for (Integer id : idList) {
            UserEntity user = userMap.get(id);
            if (user.getAccountType() == 2) {
                toResetList.add(id);
            }
        }
        // 重置密码
        if (toResetList.size() > 0) {
            LambdaUpdateWrapper<UserEntity> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.in(UserEntity::getId, toResetList);
            updateWrapper.set(UserEntity::getPassword, "000000");
            updateWrapper.set(UserEntity::getUpdateTime, new Date());
            userMapper.update(updateWrapper);
        }
        return Result.success(String.format("成功重置用户%d个，其中有%d个管理员不能重置", toResetList.size(), idList.size() - toResetList.size()));
    }


}